package com.lms.logistics_management_system.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lms.logistics_management_system.common.Constants;
import com.lms.logistics_management_system.common.Result;
import com.lms.logistics_management_system.controller.dto.*;
import com.lms.logistics_management_system.entity.*;
import com.lms.logistics_management_system.mapper.*;
import com.lms.logistics_management_system.mapper.dto.ItemListDto;
import com.lms.logistics_management_system.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Validated
@Slf4j
@Service
public class ReservationService extends ServiceImpl<ReservationMapper, Reservation> {

    @Autowired
    ReservationItemMapper reservationItemMapper;
    @Autowired
    ReservationMapper reservationMapper;
    @Autowired
    ComboMapper comboMapper;
    @Autowired
    TeamReservationMapper teamReservationMapper;

    @Autowired
    DoctorMapper doctorMapper;

    public List<ReservationItemsDto> getAllResItemInfo(String openId){
        List<ReservationItemDto> reservationItemDtoList;
        List<ReservationItemsDto> reservationItemsDtoList;
        try {
            reservationItemDtoList = reservationItemMapper.getAllResItemInfo(openId);
            //将同订单的item写入列表，返回列表嵌套列表形式
            reservationItemsDtoList = changetoList(reservationItemDtoList);

        }catch(Exception e){
            throw new ServiceException(Constants.CODE_500,"获取预约订单失败");
        }
        return reservationItemsDtoList;
    }
    //将reservationItemDto类整理为reservationItemsDto类
    public List<ReservationItemsDto> changetoList(List<ReservationItemDto> reservationItemDtoList){
        Map<Integer, ReservationItemsDto> resultMap = new HashMap<>();
        for (ReservationItemDto reservationItemDto: reservationItemDtoList) {
            Integer finished = reservationItemDto.getReservationItemResultComeout();
            Integer reservationId = reservationItemDto.getReservationId();
            ReservationItemsDto reservationItemsDto = resultMap.get(reservationId);
            if (reservationItemsDto == null) {
                reservationItemsDto = new ReservationItemsDto();
                reservationItemsDto.setReservationId(reservationItemDto.getReservationId());
                reservationItemsDto.setReservationSex(reservationItemDto.getReservationSex());
                reservationItemsDto.setReservationBuyPrice(reservationItemDto.getReservationBuyPrice());
                reservationItemsDto.setReservationBuyTime(reservationItemDto.getReservationBuyTime());
                reservationItemsDto.setReservationIsMarried(reservationItemDto.getReservationIsMarried());
                reservationItemsDto.setReservationAppointmentTime(reservationItemDto.getReservationAppointmentTime());
                reservationItemsDto.setReservationPhoneNumber(reservationItemDto.getReservationPhoneNumber());
                reservationItemsDto.setReservationIdNumber(reservationItemDto.getReservationIdNumber());
                reservationItemsDto.setTeamReservationId(reservationItemDto.getTeamReservationId());
                reservationItemsDto.setUserOpenid(reservationItemDto.getUserOpenid());
                reservationItemsDto.setReservationName(reservationItemDto.getReservationName());
                reservationItemsDto.setItemDtoList(new ArrayList<>());
                reservationItemsDto.setReservationItemResultComeout(1);//默认订单项目都完成
                resultMap.put(reservationId, reservationItemsDto);
            }

            if (reservationItemDto.getItemId()!=null){
                ItemDto itemDto = new ItemDto();
                itemDto.setItemId(reservationItemDto.getItemId());
                itemDto.setItemPrice(reservationItemDto.getItemPrice());
                itemDto.setItemName(reservationItemDto.getItemName());
                itemDto.setFinished(finished);
                if(finished==0){ //订单有项目没完成，设置
                    reservationItemsDto.setReservationItemResultComeout(0);
                }
                reservationItemsDto.getItemDtoList().add(itemDto);
            }
        }
        return new ArrayList<>(resultMap.values());
    }



    public TeamReservation buyTeamReservation(TeamReservationDto teamReservationDto){
        TeamReservation teamReservation = new TeamReservation();
        teamReservation.setTeamNumber(teamReservationDto.getTeamNumber());
        teamReservation.setComboId(teamReservationDto.getComboId());
        teamReservation.setUserOpenid(teamReservationDto.getUserOpenid());
        teamReservation.setAvailableNumber(teamReservationDto.getTeamNumber());
        teamReservation.setTeamLeaderName(teamReservationDto.getTeamLeaderName());
        //团队预约折扣由触发器生成
        try {
            teamReservationMapper.insert(teamReservation);
            System.out.println("===========插入后返回的团队预约id:" + teamReservation.getTeamReservationId());
            double comboPrice = comboMapper.selectComboPrice(teamReservationDto.getComboId());
            System.out.println("===========搜寻原comboprice:" + comboPrice);
            TeamReservation teamReservation1 = teamReservationMapper.selectById(teamReservation.getTeamReservationId());
            double discount = teamReservation1.getDiscount();
            double totalprice = comboPrice * teamReservation.getTeamNumber()*discount;
            System.out.println("===========插入后返回的团队预约总价:" + totalprice);
            teamReservation.setReservationBuyPrice(totalprice);
            teamReservation.setDiscount(discount);
            teamReservationMapper.updateById(teamReservation);
        }catch(Exception e){
            throw new ServiceException(Constants.CODE_500,"添加团队预约失败");
        }
        return teamReservation;
    }



//    Map<String,Object> res = new HashMap<>();
//    List<DepartmentItemDto> departmentItemDto;
//        try {
//        //获取所有的项目和检测类型
//        departmentItemDto=doctorMapper.getDiagnosticByReservationId(reservationId);
//        //将departmentItemDto类整理为measure类
//        List<DiagnosticResult>data = change(departmentItemDto);
//        res.put("reservationId",reservationId);
//        res.put("data",data);

    public List<Reservation> queryRes(){ //查询整表数据
        List<Reservation> reservationList;
        try {
            reservationList = reservationMapper.selectList(null);
        }catch(Exception e){
            throw new ServiceException(Constants.CODE_500,"获取预约订单失败");
        }
        return reservationList;
    }

    public Result buyChangeReservation(ReservationDto resdto) {
        Integer reservationId = resdto.getReservationId();//自增
        String reservationAppointmentTime = resdto.getReservationAppointmentTime();
        LocalDateTime reservationBuyTime = resdto.getReservationBuyTime();//可设置NULL
        String userOpenid = resdto.getUserOpenid();
        String reservationName = resdto.getReservationName();
        String reservationIdNumber = resdto.getReservationIdNumber();
        String reservationPhoneNumber = resdto.getReservationPhoneNumber();
        String reservationSex = resdto.getReservationSex();
        Integer reservationIsMarried = resdto.getReservationIsMarried();
        double reservationBuyPrice = resdto.getReservationBuyPrice();
        Integer comboId= resdto.getComboId();
        Integer teamReservationId=resdto.getTeamReservationId();

        try{
            if (teamReservationId!=null){
                System.out.println("原价格： "+ reservationBuyPrice);
                TeamReservation teamReservation = teamReservationMapper.selectTeamReservation(teamReservationId);
                if(teamReservation!=null){
                    double discount = teamReservation.getDiscount();
                    reservationBuyPrice = reservationBuyPrice * discount;
                    System.out.println("折扣 "+ discount+" 后价格： "+ reservationBuyPrice);
                }else{
                    return Result.error(Constants.CODE_600,"团队折扣id不存在！预约失败");
                }
            }
            if(!checkDailyCapacity(resdto)) return Result.error(Constants.CODE_600,"当日预约人数已满，预约失败！");
            Reservation reservation_new = new Reservation(reservationId, reservationAppointmentTime, reservationBuyPrice, reservationBuyTime, userOpenid, reservationName, reservationIdNumber, reservationPhoneNumber, reservationSex, reservationIsMarried,comboId
           ,teamReservationId);
            saveOrUpdate(reservation_new);//根据主键查询，如果查出来的结果为0，那么就执行插入操作，如果查出来的结果不为0，则执行更新操作
            return Result.success(reservation_new);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"预约订单添加/修改失败");//（可能为数据库外键等限制）
        }
    }
    //法1
//        if (reservationMapper.selectById(reservationId) == null) {
//            reservationMapper.insert(reservation_new);
//        }else{
//            save(reservation_new);
//        }
    //法2
//            reservationMapper.insert(reservation_new);

    public boolean checkDailyCapacity(ReservationDto resdto){//按照医生数量后台限制预定
        int dockerNum = doctorMapper.selectList(null).size();
        String reservationAppointmentTime = resdto.getReservationAppointmentTime();
        LambdaQueryWrapper<Reservation> lqw = Wrappers.lambdaQuery();
        lqw.eq(Reservation::getReservationAppointmentTime, reservationAppointmentTime);
        int reservationDaily = reservationMapper.selectList(lqw).size();
        return dockerNum * 10 >= reservationDaily;
    }

//    public List<Reservation> getClassifiedReservationsByOpenid(String openId,Integer finished){ //注意finished 为0和1 0为未完成
//        List<Reservation> reservationList;
//        try{
//                reservationList = reservationMapper.getClassifiedReservationsByOpenid(openId,finished);
//            }catch(Exception e){
//                throw new ServiceException(Constants.CODE_500,"获取预约订单失败");
//        }
//        return reservationList;
//    }

    //根据openId获取订单信息
//    public Reservation getReservationByOpenid(String openId){
//        System.out.println("=========================openId:"+openId);
//
//        return reservationMapper.getByOpenId(openId);
//    }

    //----------------以下对应检中------------------

    public List<DepartmentAndItemDto> getAllItemList() {
        List<ItemListDto> itemListDtoList;
        try {
            itemListDtoList =reservationMapper.getAllItemList();
        }catch(Exception e){
            throw new ServiceException(Constants.CODE_500,"获取科失败");
        }
        //处理格式，返回list套list的格式
        List<DepartmentAndItemDto> departmentAndItemDtoList=new ArrayList<>();
        Integer departmentId=-1;

        for (int i = 0; i<itemListDtoList.size(); i++){
            ItemListDto itemListDto=itemListDtoList.get(i);

               if(!departmentId.equals(itemListDto.getDepartmentId())){
                   DepartmentAndItemDto departmentAndItemDto=new DepartmentAndItemDto();
                   //第一个，设置科号，科名
                   departmentAndItemDto.setDepartmentId(itemListDto.getDepartmentId());
                   departmentAndItemDto.setDepartmentName(itemListDto.getDepartmentName());
                   //清空list表,并加入一个元素
                   List<ItemDto>itemDtoList=new ArrayList<>();
                   ItemDto itemDto=new ItemDto();
                   itemDto.setItemPrice(itemListDto.getItemPrice());
                   itemDto.setItemId(itemListDto.getItemId());
                   itemDto.setItemName(itemListDto.getItemName());
                   itemDtoList.add(itemDto);
                   //将表设置
                   departmentAndItemDto.setDepartmentItem(itemDtoList);
                   //将对象加入到list中
                   departmentAndItemDtoList.add(departmentAndItemDto);
               }else{
                    //将项目加入到室内
                   int last = departmentAndItemDtoList.size()-1;
                   List<ItemDto>itemDtoList=new ArrayList<>();
                   DepartmentAndItemDto departmentAndItemDto = departmentAndItemDtoList.get(last);
                   itemDtoList=departmentAndItemDto.getDepartmentItem();
                   ItemDto itemDto=new ItemDto();
                   itemDto.setItemPrice(itemListDto.getItemPrice());
                   itemDto.setItemId(itemListDto.getItemId());
                   itemDto.setItemName(itemListDto.getItemName());
                   itemDtoList.add(itemDto);
                   departmentAndItemDto.setDepartmentItem(itemDtoList);
                   departmentAndItemDtoList.set(last,departmentAndItemDto);
               }
            departmentId=itemListDto.getDepartmentId();
        }
       return departmentAndItemDtoList;
    }

    //对应检中 以有订单 继续添加时对于reservationitem的操作
    //添加项目到订单<!--    添加项目到订单1、更改订单价格2、在订单和item的对应表中插入一行-->
    public boolean addItemToReservation(Integer reservationId, Integer itemId) {
        return reservationMapper.addItemToReservation(reservationId,itemId);
    }



}
